var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js');
// 接入支付宝沙箱
const alipaySdk = require('../db/alipay.js');
const AlipayFormData = require('alipay-sdk/lib/form').default


/* 获取当前用户购物车列表 */
router.post('/api/selectCart', function(req, res, next) {
	let phone = req.body.phone
	// 根据电话查找当前用户
	connection.query(`select * from user where phone = "${phone}"`,
		function(er, ress) {
			if (er) throw er
			let userId = ress[0].id //当前用户id
			connection.query(`select * from goods_cart where uId = ${userId}`, function(error, results) {
				if (error) throw error
				res.send({
					data: {
						results
					}
				})
			})
		})
})

/* 更新购物车选择数量 */
router.post('/api/updateCartNum', function(req, res, next) {
	let phone = req.body.phone
	let goodsId = req.body.goodsId
	let num = req.body.num //用户输入的商品数量
	// 根据电话查找当前用户
	connection.query(`select * from user where phone = "${phone}"`,
		function(er, ress) {
			if (er) throw er
			let userId = ress[0].id //当前用户id
			connection.query(`select * from goods_cart where uId = ${userId} and goodsId=${goodsId}`,
				function(error, results) {
					if (error) throw error
					let curNum = results[0].num //当前的数量
					let id = results[0].id
					// 修改数据库中的数量
					connection.query(
						`update goods_cart set num = replace(num,${curNum},${num}) where id =${id}`,
						function(er, result) {
							if (er) throw er
							res.send({
								data: {
									success: true,
								}
							})
						})
				})
		})
})


/* 加入购物车 */
router.post('/api/addCart', function(req, res, next) {
	let phone = req.body.phone
	let goodsId = req.body.goods_id
	let num = req.body.num //用户输入的商品数量

	// 根据电话查找当前用户
	connection.query(`select * from user where phone = "${phone}"`,
		function(er, ress) {
			if (er) throw er
			let userId = ress[0].id //当前用户id
			// 用户选择的商品是否在商品表中
			connection.query(`select * from goods_search where id = ${goodsId}`,
				function(error, results) {
					if (error) throw error
					let data = {
						name: results[0].name,
						imgUrl: results[0].imgUrl,
						price: results[0].price
					}
					// 查询当前用户是否添加过这个商品
					connection.query(
						`select * from goods_cart where uId = ${userId} and goodsId = ${goodsId}`,
						function(er, result) {
							if (er) throw er
							if (result.length > 0) {
								// 当前用户加入过本商品,只需要更新数量
								let cartNum = result[0].num
								let cartId = result[0].id
								connection.query(
									`update goods_cart set num = replace(num,${cartNum},${parseInt(cartNum)+parseInt(num)}) where id = ${cartId}`,
									function(error, results) {
										if (error) throw error
										res.send({
											data: {
												success: true,
												msg: '加入成功'
											}
										})
									})
							} else {
								// 当前用户没有加入过本商品，需要添加
								connection.query(
									`insert into goods_cart (uId,goodsId,name,imgUrl,price,num) values (${userId},${goodsId},'${data.name}','${data.imgUrl}',${data.price},${num})`,
									function(error, results) {
										if (error) throw error
										res.send({
											data: {
												success: true,
												msg: '加入成功'
											}
										})
									})
							}
						})
				})
		})
})

/* 删除购物车数据 */
router.post('/api/delCart', function(req, res, next) {
	let goods_id = req.body.goods_id
	for (var i = 0; i < goods_id.length; i++) {
		let ele = goods_id[i]
		connection.query(`delete from goods_cart where id = ${ele}`,
			function(er, results) {
				if (er) throw er
			})
	}
	//此处将send语句放在for循环外，防止多次执行send报错
	res.send({
		data: {
			success: true,
			msg: '删除成功'
		}
	})
})

/* 生成订单 */
router.post('/api/addOrder', function(req, res) {
	let phone = req.body.phone
	let goodsArrs = JSON.parse(req.body.goodsArr)
	// 生成订单号
	function generateOrderNumber() {
		const date = new Date();
		const year = date.getFullYear().toString();
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		const hours = date.getHours().toString().padStart(2, '0');
		const minutes = date.getMinutes().toString().padStart(2, '0');
		const seconds = date.getSeconds().toString().padStart(2, '0');
		const randomNum = Math.floor(Math.random() * 100000).toString().padStart(5, '0');
		return `${year}${month}${day}${hours}${minutes}${seconds}${randomNum}`;
	}
	const orderNumber = generateOrderNumber(); // 订单号
	var goodsName = [] //商品名称
	let goodsPrice = 0 //商品总价
	let goodsNum = 0 //商品总数

	goodsArrs.forEach(i => {
		goodsName.push(i.name)
		goodsNum += i.num
		goodsPrice += i.num * i.price
	})
	// 根据电话查找当前用户
	connection.query(`select * from user where phone = "${phone}"`, function(error, results) {
		if (error) throw error
		let userId = results[0].id //当前用户id
		// 添加订单信息到数据库
		connection.query(
			`insert into order_data (user_id,order_id,name,num,price,status) values (${userId},'${orderNumber}','${goodsName}',${goodsNum},${goodsPrice},'1')`,
			function(err, result) {
				if (err) throw err
				// 查询订单号
				connection.query(
					`select * from order_data where user_id = ${userId} and order_id = "${orderNumber}"`,
					function(err, ress) {
						if (err) throw err
						res.send({
							data: {
								success: true,
								data: ress
							}
						})
					})
			})
	})
})


/* 提交订单后修改订单状态 */
router.post('/api/submitOrder', function(req, res) {
	let phone = req.body.phone
	let orderId = req.body.orderId
	let shopIds = JSON.parse(req.body.shopIds)
	// 根据电话查找当前用户
	connection.query(`select * from user where phone = "${phone}"`, function(error, results) {
		if (error) throw error
		let userId = results[0].id //当前用户id
		connection.query(
			`select * from order_data where user_id = ${userId} and order_id = "${orderId}"`,
			function(error, result) {
				if (error) throw error
				let id = result[0].id //订单id
				// 修改订单状态
				connection.query(
					`update order_data set status = replace(status,'1','2') where id=${id}`,
					function(err, results) {
						if (err) throw err
						// 清除购物车数据
						shopIds.forEach(v => {
							connection.query(`delete from goods_cart where id = ${v}`,
								function(er, results) {
									if (er) throw er
								})
						})
						res.send({
							data: {
								success: true
							}
						})
					})
			})
	})
})

/* 支付 */
router.post('/api/payment', function(req, res) {
	let orderId = req.body.orderId;
	let price = req.body.price;
	let goodsName = JSON.parse(req.body.goodsName).join('');
	const formData = new AlipayFormData()
	formData.setMethod('get')
	formData.addField('bizContent', {
		outTradeNo: orderId, //订单号
		productCode: 'FAST_INSTANT_TRADE_PAY', //写死的
		totalAmount: price, //金额
		subject: goodsName //商品名称
	})
	//支付成功或者失败打开的页面
	formData.addField('returnUrl', 'http://www.xuexiluxian.cn/');
	const result = alipaySdk.exec(
		'alipay.trade.page.pay', {}, {
			formData: formData
		},
	);
	result.then(resp => {
		res.send({
			data: {
				code: 200,
				success: true,
				paymentUrl: resp
			}
		})
	})
})
module.exports = router;
